package com.yaowk.system.server.service.impl;

import com.yaowk.common.api.StatusDict;
import com.yaowk.system.api.model.User;
import com.yaowk.system.server.entity.SysMenu;
import com.yaowk.system.server.entity.SysResource;
import com.yaowk.system.server.entity.SysRole;
import com.yaowk.system.server.entity.SysUser;
import com.yaowk.system.server.service.base.UserServiceBase;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl extends UserServiceBase {


    @Override
    @Transactional
    public List<Long> findPermissionsByUserId(Long id) {
        SysUser sysUser = getDao().findOne(id);
        Set<SysRole> roles = sysUser.getRoles();
        List<Long> permissions = new ArrayList<Long>();
        for (SysRole sysRole : roles) {
            Set<SysMenu> menus = sysRole.getMenus();
            for (SysMenu sysMenu : menus) {
                Set<SysResource> resources = sysMenu.getResources();
                for (SysResource sysResource : resources) {
                    permissions.add(sysResource.getId());
                }
            }
        }
        return permissions;
    }

    @Override
    public User findByUsername(String s) {
        SysUser sysUser = getDao().findByUsername(s);
        User user = entity2Model(sysUser);
        user.setPassword(sysUser.getPassword());
        return user;
    }

    @Override
    public void deleteById(Long aLong) {
        SysUser sysUser = getDao().findOne(aLong);
        sysUser.setStatus(StatusDict.FALSE);
        getDao().save(sysUser);
    }

    @Override
    public User entity2Model(SysUser entity) {
        User user = super.entity2Model(entity);
        if (isNotEmpty(user)) {
            user.setPassword(null);
        }
        return user;
    }
}